#include "yktoken.hpp"

void yktoken::ykcreate(name admin, name symbol)
{
    // 权限检测
    require_auth(admin);
    // 对表进行操作
    supplys sly(get_self(), admin.value);
    auto itr = sly.find(symbol.value);

    check(itr == sly.end(), "token symbol already exists");

    sly.emplace(admin, [&](auto &g){
        g.symbol = symbol;
        g.totalSupply = 0;
    });

}

// 发行：操作2个表
void yktoken::ykissue(name admin, name symbol, uint64_t supply)
{
    // 权限检测
    require_auth(admin);
    // 对表进行操作
    supplys sly(get_self(), admin.value);
    auto itr = sly.find(symbol.value);

    check(itr != sly.end(), "token symbol does not exists");

    sly.modify(itr, admin, [&](auto &g){
        g.totalSupply += supply;
    });

    // 余额表操作
    balances bal(get_self(), symbol.value);
    auto itr2 = bal.find(symbol.value); // 符号也可以作为虚拟人，发行者

    if(itr2 == bal.end()) {
        bal.emplace(admin, [&](auto &g){
            g.username = symbol;
            g.amount  = supply;
        });
    } else {
        bal.modify(itr2 ,admin, [&](auto &g){
            g.amount  += supply;
        });
    }
}

void yktoken::yktransfer(name admin, name symbol, name from, name to, uint64_t amount)
{
    // 权限检测
    require_auth(admin);

    balances bal(get_self(), symbol.value);
    auto itr = bal.find(from.value); // 

    check(itr != bal.end(), "from does not have token");
    check(itr->amount >= amount, "from' balance not enough");

    // from = from - amount; to = to + amount;
    bal.modify(itr, admin, [&](auto &g){
        g.amount -= amount;
    });

    itr = bal.find(to.value);

    if(itr == bal.end()) {
        bal.emplace(admin, [&](auto &g){
            g.username = to;
            g.amount   = amount;
        });
    } else {
        bal.modify(itr, admin, [&](auto &g){
            g.amount   += amount;
        });
    }

}

uint64_t yktoken::ykbalanceof(name admin, name symbol, name who)
{
    // 权限检测
    require_auth(admin);
    balances bal(get_self(), symbol.value);
    auto itr = bal.find(who.value); // 
    if(itr != bal.end()) {
        return itr->amount;
    }
    return 0;
}

uint64_t yktoken::yksupply(name admin, name symbol)
{
    // 权限检测
    require_auth(admin);
    // 对表进行操作
    supplys sly(get_self(), admin.value);
    auto itr = sly.find(symbol.value);

    if(itr != sly.end()) {
        return itr->totalSupply;
    }

    return 0;
}
